import React, { useState, useEffect, useRef, useMemo } from "react";
import { message, Tabs, Table, Pagination, Space } from "antd";
import { Panel, FormSelect, UploadModal } from "@/components";
import { useEventListener } from "ahooks";
import dictionary, { echartTypes } from "@/config/character";
import ajax from "@/services";
import "./index.scss";

/**
 * @description 国家gdp
 **/
export default function Statistic(props) {
  const [tabItems, setTabItems] = useState([
    { label: "世界", key: "item-1" },
    { label: "欧洲", key: "item-2" },
    { label: "美洲", key: "item-3" },
    { label: "亚洲", key: "item-4" },
    { label: "非洲", key: "item-5" },
    { label: "澳大利亚", key: "item-6" },
    { label: "主要的", key: "item-7" },
  ]);
  const [ajaxLoading, setAjaxLoading] = useState(false);
  const [resultData, setResultData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [scrollHeight, setScrollHeight] = useState(500);
  const columnsRef = useRef([]);
  const sorterArrRef = useRef([]);
  const averageRef = useRef([]);
  // 获取颜色函数，根据值与平均值的偏离程度设置颜色
  function getColor(value, average) {
    console.log(value, average);
    const diff = Number(value) - Number(average);
    if (diff > 0) {
      // 高于平均值，用冷色（蓝色）
      return `rgb(100, 100, ${Math.min(255, 150 + diff * 5)})`;
    } else {
      // 低于平均值，用暖色（红色）
      return `rgb(${Math.min(255, 150 - diff * 5)}, 100, 100)`;
    }
  }
  // 获取列表数据
  const getList = (params = tabItems[0].label) => {
    setAjaxLoading(true);
    ajax
      .getStatistic({ tag: params })
      .then(
        (res) => {
          if (res.data) {
            let resData = res.data;
            let resTitle = resData.title.map((item, index) => {
              return {
                title: item,
                dataIndex: `statistic${index}`,
                align: "center",
                render: (text, record, i) =>
                  index === 0 ? (
                    <span
                      onClick={() => {
                        handleSort(text, record);
                      }}
                      style={{ cursor: "pointer" }}
                    >
                      {text}
                    </span>
                  ) : (
                    <span
                      style={{
                        color: `${getColor(
                          text,
                          averageRef.current.get(`${record.statistic0}`)
                        )}`,
                      }}
                    >
                      {text}
                    </span>
                  ),
              };
            });
            columnsRef.current = resTitle;
            setColumns(resTitle);
            let sortMapArr = new Map();
            let averageArr = new Map();
            let resValue = resData.value.map((item, index) => {
              // 设置初始排序状态
              sortMapArr.set(`${item[0]}`, 0);
              // 设置初始平均值
              averageArr.set(
                `${item[0]}`,
                item
                  .slice(1)
                  .reduce((sum, value) => Number(sum) + Number(value), 0) /
                  (item.length - 1)
              );
              // 设置表格数据
              let obj = {};
              item.forEach((elememt, i) => {
                obj[`statistic${i}`] = elememt;
              });
              return { ...obj, key: `statistic${index}` };
            });
            sorterArrRef.current = sortMapArr;
            averageRef.current = averageArr;
            setResultData(resValue);
            handleResize();
          } else {
            setResultData([]);
          }
        },
        (err) => {
          console.log(err);
          setResultData([]);
        }
      )
      .finally(() => {
        setAjaxLoading(false);
        let newTabItems = tabItems.map((item) => {
          return {
            ...item,
            disabled: false,
          };
        });
        setTabItems(newTabItems);
      });
  };
  const onChange = (key) => {
    console.log(key);
    getList(tabItems.find((item) => item.key === key).label);
    let newTabItems = tabItems.map((item) => {
      return {
        ...item,
        disabled: true,
      };
    });
    setTabItems(newTabItems);
  };
  // 排序
  const handleSort = (text, data) => {
    console.log(sorterArrRef.current.get(text));
    console.log(text, data);
    let sortOrder = sorterArrRef.current.get(text);
    let newSortOrder = (sortOrder + 1) % 3;
    sorterArrRef.current.set(`${text}`, newSortOrder);
    // Step 1: 提取第一个对象的 statistic1 到 statistic8，并按值升序排序
    let sortedKeys = [];
    if (newSortOrder === 1) {
      sortedKeys = Object.entries(data)
        .filter(([key]) => key.startsWith("statistic") && key !== "statistic0") // 过滤出 statistic1 到 statistic8
        .sort(([, a], [, b]) => Number(a) - Number(b)) // 使用 Number() 进行比较
        .map(([key]) => key); // 仅保留键
    } else if (newSortOrder === 2) {
      sortedKeys = Object.entries(data)
        .filter(([key]) => key.startsWith("statistic") && key !== "statistic0") // 过滤出 statistic1 到 statistic8
        .sort(([, a], [, b]) => Number(b) - Number(a)) // 使用 Number() 进行比较
        .map(([key]) => key); // 仅保留键
    } else {
      setColumns(columnsRef.current);
      return;
    }

    // Step 2: 根据排序后的 key 顺序调整所有对象
    const reorderedColumns = columnsRef.current
      .filter(
        (item) =>
          item.dataIndex === "statistic0" || sortedKeys.includes(item.dataIndex)
      ) // 保留 statistic0 和排序后的键
      .sort(
        (a, b) =>
          sortedKeys.indexOf(a.dataIndex) - sortedKeys.indexOf(b.dataIndex)
      ); // 根据排序后的索引重新排列
    setColumns(reorderedColumns);
  };
  const handleResize = () => {
    const tableWarp = document.querySelector(".result-table");
    if (tableWarp) {
      let tableHight = tableWarp.clientHeight - 143;
      setScrollHeight(tableHight);
    }
  };
  useEventListener("resize", handleResize, { target: window });

  useEffect(() => {
    getList();
    return () => {};
  }, []);

  return (
    <div className="statistic-page">
      <Panel className="result-body">
        <div className="result-header">
          <Tabs onChange={onChange} type="card" items={tabItems} />
        </div>
        <div className="result-table">
          <Table
            scroll={{ y: scrollHeight, x: "auto" }}
            columns={columns}
            dataSource={resultData}
            bordered
            loading={ajaxLoading}
            pagination={false}
            rowClassName={(record, index) =>
              (index + 1) % 2 === 0 ? "even-row" : "odd-row"
            }
          />
        </div>
      </Panel>
    </div>
  );
}
